var pathRequestUrl;
var page_size = 20;
var albumRecord;
var albumObj;
var gridAlbum;
var bbarAlbum;
var row_current = -1;
var col_current = -1;

Ext.onReady(function(){
	Ext.QuickTips.init();
    pathRequestUrl = 'ListAlbumData.php';
    
	function isEmpty(obj){
		if (typeof obj == 'undefined' || obj === null || obj === '') 
			return true;
		if (typeof obj == 'number' && isNaN(obj)) 
			return true;
		if (obj instanceof Date && isNaN(Number(obj))) 
			return true;
		return false;
	};

	var formatDate = function(value){
		if (isEmpty(value)) 
			return '';
		try {
			return value ? ((value.dateFormat('d/m/Y') != '01/01/1970') ? value.dateFormat('d/m/Y') : '') : '';
		} 
		catch (e) {
			console.debug(e);
		}
	};
	//--------------------------	
	Ext.ns('Extensive.grid');
	Extensive.grid.ItemDeleter = Ext.extend(Ext.grid.RowSelectionModel, {
		width: 30,		
		sortable: false,
		dataIndex: 0, // this is needed, otherwise there will be an error		
		menuDisabled: true,
		fixed: true,
		id: 'deleter',		
		initEvents: function(){
			Extensive.grid.ItemDeleter.superclass.initEvents.call(this);
			this.grid.on('cellclick', function(grid, rowIndex, columnIndex, e){
				/*if(columnIndex == grid.getColumnModel().getIndexById('deleter')) {
					var record = grid.getStore().getAt(rowIndex);
					grid.getStore().remove(record);
					grid.getView().refresh();
				}*/
				if (columnIndex == grid.getColumnModel().getIndexById('deleter')) {
                    var record = grid.getStore().getAt(rowIndex);
                    if (record.data.album_id == 0) 
                        return false;
                    Ext.Msg.show({
                        title: 'Xác nhận',
                        buttons: Ext.MessageBox.YESNO,
                        icon: Ext.MessageBox.QUESTION,
                        msg: "Bạn có chắc là muốn xóa Album <b>" + record.data.album_name + "</b> không ?",
                        fn: function(btn){
                            if (btn == 'yes') {
                                deleteAlbum(record);
                            }
                        }
                    });                    
                }
			});
		},		
		renderer: function(v, p, record, rowIndex){
			return '<div class="extensive-remove" style="width: 15px; height: 16px;"></div>';
		}
	});	
	var itemDeleter = new Extensive.grid.ItemDeleter();
	
	//-----------------------------
    albumRecord = [
        {name: 'album_id', type: 'string'},   
        {name: 'album_number', type: 'string'},
        {name: 'album_name', type: 'string'},
        {name: 'album_author', type: 'string'},
		{name: 'created_date', type: 'date'}
	];
    
    albumObj = Ext.data.Record.create(albumRecord);
    
    var Album = {
        add: function(){
    		addNewAlbum();
			//bbarAlbum.moveLast();
        },
        remove: function(){ 
			
        },        
        find: function(){  
			gridAlbum.getStore().load();		
        },
		print: function(){
			
		}
    };
    
    var storeAlbum = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'id'
        }, albumObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
        
    storeAlbum.on('beforeload', function(){
        storeAlbum.baseParams.action = 'get';
        storeAlbum.baseParams.start = 0;
        storeAlbum.baseParams.limit = page_size;
        storeAlbum.baseParams.srch_album_number = Ext.getCmp('srch_album_number').getValue();
		storeAlbum.baseParams.srch_album_name = Ext.getCmp('srch_album_name').getValue();
		storeAlbum.baseParams.srch_album_author = Ext.getCmp('srch_album_author').getValue();
    });
 
	var tbarObject = new Ext.Panel({
		items:[{
			xtype: 'toolbar',
			id: 'tbar1',
			items:[{
					xtype: 'tbtext',
					width: 60,
					text: 'Mã Album '
				}, {
					xtype: 'textfield',
					id: 'srch_album_number',
					width: 100,
					listeners: {
	                    change: function(e){
	            			gridAlbum.getStore().load();
	                    }
	                }
				}, '-', {
					xtype: 'tbtext',
					width: 65,
					text: 'Tên Album ',
				}, {
					xtype: 'textfield',
					id: 'srch_album_name',
					width: 250,
					listeners: {
	                    change: function(e){
	            			gridAlbum.getStore().load();
	                    }
	                }
				}, '-', {
					xtype: 'tbtext',
					width: 65,
					text: 'Tác giả ',
				}, {
					xtype: 'textfield',
					id: 'srch_album_author',
					width: 150,
					listeners: {
	                    change: function(e){
	            			gridAlbum.getStore().load();
	                    }
	                }
				}, '-', {
					text: 'Tìm Kiếm',
					id: 'find_album_action',
					cls: 'x-btn-text-icon',
					icon: 'images/icons/find.png',
					style: 'padding-left: 5px;',
					handler: Album.find
				}]			    
			},{
				xtype: 'toolbar',
				id: 'tbar3',
				items:[{
					text: 'Thêm',
					id: 'add_album',
					cls: 'x-btn-text-icon',
					icon: 'images/icons/add.png',
					handler: Album.add
				}/*,'-',{
					text: 'In',
					id: 'printer_add',
					cls: 'x-btn-text-icon',
					icon: 'images/icons/printer.png',
					handler: Album.print
				},'->',*/]
			}]
	});
	
    var cmbPerPage = new Ext.form.ComboBox({
        name: 'perpage',
        width: 80,
        store: new Ext.data.SimpleStore({
            data: [[20, '20'], [50, '50'], [100, '100'], [300, '300'], [500, '500'], [1000, '1000']],
            id: 0,
            fields: ['id', 'value']
        }),
        mode: 'local',
        value: '20',
        listWidth: 80,
        triggerAction: 'all',
        displayField: 'value',
        valueField: 'value',
        editable: false,
        forceSelection: true
    });
    
    cmbPerPage.on('select', function(combo, record){
        bbarAlbum.pageSize = parseInt(record.get('id'), 10);
        bbarAlbum.doLoad(bbarAlbum.cursor);
    }, this);
    
    bbarAlbum = new Ext.PagingToolbar({
        store: storeAlbum, // the store you use in your grid
        displayInfo: true,
        pageSize: page_size,
        id: 'bbar_album',
        items: ['-', 'Số tin', cmbPerPage],
		listeners: {
            change: function(tb, data){
//                if (data.activePage == data.pages) {
//                    if (gridAlbum.getStore().getCount() > 0) {
//                        addNewAlbum(gridAlbum.getStore().getCount(), 3, true);
//                    }else{
//                    	addNewAlbum(0, 3, true);
//                    }
//                }
            }
        }
    });
    
    var cmObject = new Ext.grid.ColumnModel({
        defaults: {
            sortable: true
        },
        columns: [new Ext.grid.RowNumberer(), itemDeleter ,{
            header: 'Mã Album',
            dataIndex: 'album_number',
			width: 100,
			editor: new Ext.form.TextField( {
				allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
			})
        }, {
            header: 'Tên Album',
            dataIndex: 'album_name',
			width: 360,
			editor: new Ext.form.TextField( {
				allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
			})
        }, {
            header: 'Tác Giả',
            dataIndex: 'album_author',
			width: 250,
			editor: new Ext.form.TextField( {
				allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
			})
        }, {
            header: 'Ngày Tạo',
            dataIndex: 'created_date',
			width: 100,
			renderer: formatDate
        }]
    });
	gridAlbum = new Ext.grid.EditorGridPanel({
    	title: '',
        id: 'gridAlbum',
        store: storeAlbum,
        cm: cmObject,
        tbar: tbarObject,
        bbar: bbarAlbum,
        stripeRows: true,
        height: 530,
        loadMask: true,
        trackMouseOver: true,
        frame: true,
        clicksToEdit: 1,
		selModel: itemDeleter,
		viewConfig: {
            forceFit: true,
            deferEmptyText: true,
            emptyText: 'No records found'
        },
        //autoHeight: true,
        listeners: {
            beforeedit: function(e){
                row_current = e.row;
                col_current = e.column;
            },
            afteredit: function(e){
                if (0 == e.record.data.album_id) {
                    insertAlbum(e);
                }
                else {
                    updateAlbum(e);
                }
            }
            
        }
    });
    
    var albumFormPanel = new Ext.FormPanel({
        id: 'list_album_panel',
        iconCls: 'form-icon',
        title: 'QL Thông Tin Album',
        frame: true,
        width: 900,
        renderTo: 'list_album',
        items: [gridAlbum]
    });     

});

/**
 * Functions --------------------------------------------------------------------------------------
 */
var addNewAlbum = function() {
	var newRecord = new albumObj({
        album_id: 0,
        album_number: null,
        album_name: null,
        album_author: null,
		created_date: new Date()
    });
        
    gridAlbum.getStore().insert(gridAlbum.getStore().getCount(), newRecord);
    gridAlbum.startEditing(gridAlbum.getStore().getCount() - 1, 2);
};

/**
 * Insert 
 * @author huudatxm
 */
var insertAlbum = function(e){
    if (!checkDataInsert(e)) 
        return;
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {               
                if(result.data.error == 1) {
            		alert('Mã album này đã tồn tại. Vui lòng chọn mã khác !.');
            		return;
            	}
                e.record.data.album_id = result.data.id;
                e.record.commit();
                /*
                addNewAlbum();
                gridAlbum.startEditing(row_current, col_current);*/
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'insert',
            album_number: e.record.data.album_number,
            album_name: e.record.data.album_name,
            album_author: e.record.data.album_author
        }
    });
};

/**
 * Update
 * @author huudatxm
 */
var updateAlbum = function(e){	
	if (!checkDataInsert(e)) 
        return;
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
            		alert('Mã album này đã tồn tại. Vui lòng chọn mã khác !.');
            		return;
            	}
                e.record.commit();
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'update',
            field: e.field,
            value: e.value,
            album_id: e.record.data.album_id
        }
    });
};

/**
 * Key Control
 * @author datnh
 */
var keyCustom = function(e){
    if (e.keyCode == 40) {
        //KeyDown	
        var store_size = gridAlbum.getStore().getCount();
        if ((store_size - 1) == row_current) {
            if (0 == gridAlbum.getStore().getAt(store_size - 1).data.album_id) {
                return false;
            }else{
            	addNewAlbum();
            	return;
            }
        }
        row_current++;
        gridAlbum.startEditing(row_current, col_current);
        gridAlbum.getSelectionModel().selectRow(row_current);
    }
    else 
        if (e.keyCode == 38) {
            //KeyUp
            if (row_current > 0) {
                row_current--;
                gridAlbum.startEditing(row_current, col_current);
                gridAlbum.getSelectionModel().selectRow(row_current);
            }
        }
};

/**
 * Delete
 * @author huudatxm
 */
var deleteAlbum = function(record){
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
                gridAlbum.getStore().remove(record);
                gridAlbum.getView().refresh();
            }
            else {
                alert('Không thể xóa vì lỗi phát sinh.');
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'delete',
            album_id: record.data.album_id
        }
    });
};

/**
 * Check data for insert
 * @author huudatxm
 */
var checkDataInsert = function(e){
    var data = e.record.data;
    return !(isEmpty(data.album_number) || isEmpty(data.album_name) || isEmpty(data.album_author));
};
